package com.red.wood.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * 解析地址
 * 
 * @author gaolei
 * @param address
 * @return 归属省份
 */

public class C3Parse {
	static Map<String, String> PCCode = null;
	static Map<String, String> PCAode = null;
	static Map<String, String> SPECCode = null;

	
	public static String addressAdscription(String address) {
		if(StringUtils.isBlank(address)) {
			return "";
		}
		if (PCCode == null || PCCode.size() <= 0) {
			PCCode = C3Parse.get3C().get(0);
			PCAode = C3Parse.get3C().get(1);
			SPECCode = C3Parse.get3C().get(2);
		}
		/*
		 * test("济南市", "山东省"); ("潍坊市", "山东省"); ("市南区", "山东省");
		 */
		String province = null, city = null, county = null;
		String provinceN = "(?<province>[^省]+省|.+自治区)";
		String cityN = "(?<city>[^自治州]+自治州|[^市]+市|[^盟]+盟|[^地区]+地区|.+区划)";
		String countyN = "(?<county>[^市]+市|[^县]+县|[^旗]+旗|.+区)";

		Matcher m = Pattern.compile(provinceN).matcher(address);
		while (m.find()) {
			province = m.group("province");
			if (province != null) {
				province = province.replace("省", "").replace("自治区", "").replace("市", "");
				break;
			}
		}

		if (province == null) {
			m = Pattern.compile(cityN).matcher(address);
			while (m.find()) {
				city = m.group("city");
  				province = PCCode.get(city);
				if (province != null) {
					break;
				}
			}
		}

		if (province == null && city == null) {
			m = Pattern.compile(countyN).matcher(address);
			while (m.find()) {
				county = m.group("county");
				province = PCAode.get(county);
				if (province != null) {
					break;
				}
			}
		}

		if (province !=null && province.length() > 3) {
			province = null;
		}
		//补充地址带有中国并且把省份括起来的,比如：中国(上海)
		if(province == null && StringUtils.isNotBlank(address)) {
			String reg = "(?<province>[^）]+）|[^\\)]+\\))";
			m = Pattern.compile(reg).matcher(address);
			while (m.find()) {
				String provinceStr = m.group("province");
				if(provinceStr.length() > 3) {
					province = SPECCode.get(provinceStr.substring(3,provinceStr.length()-1));
					if(province == null) {
						province = PCCode.get(provinceStr.substring(3,provinceStr.length()-1));//表示带了省
					}
				}
			}
		}
		
		//补充地址没有带省和市或者中国开头的或者特有的关键字(中关村)开头的等等,县暂时不考虑
		if(province == null && StringUtils.isNotBlank(address)) {
			if(StringUtils.startsWith(address, "中国")) {
				address = address.substring(2,address.length());
			}
			if(address.length() >= 2) {
				province = SPECCode.get(address.substring(0, 2));//比如：江西xx
				if(province == null && address.length() >= 3) {
					province = SPECCode.get(address.substring(0, 3));//比如：内蒙古xx
					if(province == null && address.length() >= 4) {
						province = SPECCode.get(address.substring(0, 4));//比如：鄂尔多斯xx
						if(province == null && address.length() >= 5) {
							province = SPECCode.get(address.substring(0, 5));//比如：延边朝鲜族xx
							if(province == null && address.length() >= 6) {
								province = SPECCode.get(address.substring(0, 6));//比如：文山壮族苗族xx
								if(province == null && address.length() >= 7) {
									province = SPECCode.get(address.substring(0, 7));//比如：恩施土家族苗族xx
									if(province == null && address.length() >= 8) {
										province = SPECCode.get(address.substring(0, 8));//比如：黔西南布依族苗族xx
									}
								}
							}
						}
					}
				}
			}
		}
		return province;
	}

	public static String ReadFile(InputStream inputStream) {
		BufferedReader reader = null;
		String laststr = "";
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			/*
			 * FileInputStream fileInputStream = new FileInputStream(Path);
			 * InputStreamReader inputStreamReader = new
			 * InputStreamReader(fileInputStream, "UTF-8");
			 */
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				laststr += tempString;
			}
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return laststr;
	}

	public static List<Map<String, String>> get3C() {
		//String JsonContext = ReadFile(C3Parse.class.getResourceAsStream("/c3.json"));
		String province = null, city = null, area = null;
		Map<String, String> PCCode = new HashMap<String, String>();
		Map<String, String> PCAode = new HashMap<String, String>();
		Map<String,String> specCode = new HashMap<String,String>();
		List<Map<String, String>> C3L = new ArrayList<Map<String, String>>();
		
		try {
			String input = IOUtils.toString(C3Parse.class.getClassLoader().getResourceAsStream("c3.json"),"UTF-8");
			JSONArray jArray = JSONArray.fromObject(input);
			//JSONArray jArray = new JSONArray(JsonContext);
			for (int i = 0; i < jArray.size(); i++) {
				JSONObject jsonObject = jArray.getJSONObject(i);
				province = jsonObject.getString("name");
				JSONArray cityArray = jsonObject.getJSONArray("city");
				JSONArray specValueArray = jsonObject.getJSONArray("specValue");
				for(int j = 0 ; j < specValueArray.size() ; j++) {
					String specValue = specValueArray.get(j).toString();
					specCode.put(specValue, province);
				}
				for (int j = 0; j < cityArray.size(); j++) {
					JSONObject cityObject = cityArray.getJSONObject(j);
					city = cityObject.getString("name");
					PCCode.put(city, province);
					JSONArray areaArray = cityObject.getJSONArray("area");
					for (int n = 0; n < areaArray.size(); n++) {
						area = areaArray.get(n).toString();
						PCAode.put(area, province);
					}
				}
			}
			C3L.add(PCCode);
			C3L.add(PCAode);
			C3L.add(specCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return C3L;
	}

	public static void main(String[] args) throws IOException {
		//System.out.println("地址是：" + addressAdscription("北京市海淀区苏州街12号西屋国际C座1203室"));
		//System.out.println("地址是：" + addressAdscription("江西鄱阳机房"));
		//System.out.println("地址是：" + addressAdscription("内蒙古机房"));
		
		String provinceN = "(?<province>[^）]+）|[^\\)]+\\))";
		String cityN = "(?<city>[^自治州]+自治州|[^市]+市|[^盟]+盟|[^地区]+地区|.+区划)";
		String countyN = "(?<county>[^市]+市|[^县]+县|[^旗]+旗|.+区)";
		String address = "中国上海自由贸易实验区郭守敬路498号8幢19号楼3层";
		if(StringUtils.startsWith(address, "中国")) {
			System.out.println(address.substring(2,address.length()));
		}
	}
}
